package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.entity.User;
import example.springboot.service.UserService;
import example.springboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin
public class AdminProfileController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 获取管理员个人资料
     */
    @GetMapping("/profile")
    public Result<Map<String, Object>> getProfile(HttpServletRequest request) {
        try {
            // 从请求头获取token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            if (token == null || token.isEmpty()) {
                return Result.error("未登录");
            }

            // 验证token并获取用户ID
            Integer userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("登录已过期，请重新登录");
            }

            // 查询用户信息
            User user = userService.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 验证是否为管理员
            if (!"admin".equals(user.getRole())) {
                return Result.error("权限不足");
            }

            // 构建返回数据（不返回密码）
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("nickname", user.getNickname());
            data.put("email", user.getEmail());
            data.put("avatarUrl", user.getAvatarUrl());
            data.put("role", user.getRole());
            data.put("status", user.getStatus());
            data.put("createdAt", user.getCreatedAt());

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取个人资料失败：" + e.getMessage());
        }
    }

    /**
     * 更新管理员个人资料
     */
    @PutMapping("/profile")
    public Result<String> updateProfile(HttpServletRequest request, @RequestBody User user) {
        try {
            // 从token获取用户ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Integer userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 查询用户
            User existUser = userService.findById(userId);
            if (existUser == null) {
                return Result.error("用户不存在");
            }

            // 验证是否为管理员
            if (!"admin".equals(existUser.getRole())) {
                return Result.error("权限不足");
            }

            // 只更新允许修改的字段
            existUser.setNickname(user.getNickname());
            existUser.setEmail(user.getEmail());
            if (user.getAvatarUrl() != null) {
                existUser.setAvatarUrl(user.getAvatarUrl());
            }

            boolean success = userService.updateUser(existUser);
            if (success) {
                // 更新localStorage中的用户信息
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新资料失败：" + e.getMessage());
        }
    }

    /**
     * 修改管理员密码
     */
    @PutMapping("/password")
    public Result<String> changePassword(HttpServletRequest request, @RequestBody Map<String, String> passwordData) {
        try {
            // 从token获取用户ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Integer userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("未登录");
            }

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");

            if (oldPassword == null || oldPassword.isEmpty()) {
                return Result.error("请输入原密码");
            }
            if (newPassword == null || newPassword.isEmpty()) {
                return Result.error("请输入新密码");
            }
            if (newPassword.length() < 6) {
                return Result.error("新密码长度至少6位");
            }

            // 查询用户
            User user = userService.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 验证是否为管理员
            if (!"admin".equals(user.getRole())) {
                return Result.error("权限不足");
            }

            // 验证原密码
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                return Result.error("原密码错误");
            }

            // 更新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            boolean success = userService.updateUser(user);

            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }
}
